package com.kunlun.gateway.filter;

import com.google.common.util.concurrent.RateLimiter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class GatewayGlobalFilter implements GlobalFilter, Ordered {

    private Logger log = LogManager.getLogger();

    private static final RateLimiter RATE_LIMITER = RateLimiter.create(10);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("GatewayGlobalFilter filter start");

        // 访问限流
        ServerHttpRequest request = exchange.getRequest();
        String requestUrl = String.valueOf(request.getPath());
        log.info("GatewayGlobalFilter filter requestUrl ===>>> " + requestUrl);
        if (!RATE_LIMITER.tryAcquire()) {
            log.info("========== GatewayGlobalFilter 访问量超载! ==========");
            ServerHttpResponse response = exchange.getResponse();
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
